package striveen.util.used.json;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import striveen.util.used.log.Log;

public final class JsonMapOrListJsonMap2JsonUtil<K, V> implements Serializable {
	private static final long serialVersionUID = 1L;

	public String map2Json(Map<K, V> data) {
		if ((data == null) || (data.size() == 0)) {
			return "{}";
		}
		StringBuilder sb = new StringBuilder("{");
		Set ks = data.keySet();
		for (Iterator iterator = ks.iterator(); iterator.hasNext();) {
			Object k = (Object) iterator.next();
			sb.append((new StringBuilder("\"")).append(k.toString())
					.append("\":").toString());
			Object v = data.get(k);
			if (null == v) {
				sb.append("\",");
			} else if (v instanceof Number) {
				sb.append(v + ",");
			} else if (v.getClass().equals(ArrayList.class)) {
				sb.append(listJsonMap2Json((List) v) + ",");
			} else if (v.getClass().equals(HashMap.class)) {
				sb.append(map2Json((Map) v) + ",");
			} else if (v.getClass().equals(JsonMap.class)) {
				sb.append(map2Json((Map) v) + ",");
			} else if (v.getClass().equals(JSONArray.class)) {
				sb.append(listJsonMap2Json((List) v) + ",");
			} else if (v.getClass().equals(JSONObject.class)) {
				sb.append(map2Json(JSONObjectToMap((JSONObject) v)) + ",");
			} else {
				sb.append("\"" + v + "\",");
			}
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append("}");
		return sb.toString();
	}

	private Map<K, V> JSONObjectToMap(JSONObject object) {

		Map<K, V> map = new HashMap<K, V>();
		Iterator it = object.keys();
		String key = "";
		while (it.hasNext()) {// 遍历JSONObject
			key = (String) it.next().toString();
			try {
				map.put((K) key, (V) object.get(key));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return map;
	}

	public String listJsonMap2Json(List<? extends Map<K, V>> data) {
		if ((data == null) || (data.size() == 0)) {
			return "[]";
		}
		StringBuilder sb = new StringBuilder("[");
		for (Map map : data) {
			sb.append(map2Json(map) + ",");
		}

		sb.deleteCharAt(sb.length() - 1);

		sb.append("]");
		return sb.toString();
	}
}